<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from "@dcloudio/uni-app"
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import { postManagementVO, postManagementApi } from '@/api/oa/postManagement'
import { getUserProfile, getUserSalary } from "@/api/system/user/profile";
import { useMessage, useToast } from 'wot-design-uni'
import FormComponent from '@/components/FormComponent/index.vue'
import { getFileName, parseArrayField, buildFileList } from '@/utils/fileUtils'



const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)
const resubmit = ref(0)

// 指定审批人
const processDefineKey = ref<string>('oa_outgoing')
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const formData = ref<postManagementVO>(
	{
		type: 0
	} as any)
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	mainContent: [],
	attachment: []
})
/** 处理类型变更 */
const handleTypeChange = async ({ value }: { value: any }) => {
	console.log('value', value);

	startUserSelectTasks.value = []
	startUserSelectAssignees.value = {}
	if (value === undefined || value === null) return
	try {
		// 根据不同类型获取不同的流程定义Key
		const processKeyMap: Record<number, string> = {
			0: 'oa_outgoing',
			1: 'oa_outgoing_outside',
			2: 'oa_erjifawen'
		}
		processDefineKey.value = processKeyMap[value] || ''
		const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
			undefined,
			processDefineKey.value
		)
		if (!processDefinitionDetail) {
			toast.error('流程模型未配置，请检查！')
			return
		}
		startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
		console.log('startUserSelectTasks.value', startUserSelectTasks.value);

		// 设置指定审批人
		if (startUserSelectTasks.value?.length > 0) {
			// 设置校验规则
			for (const userTask of startUserSelectTasks.value) {
				startUserSelectAssignees.value[userTask.id] = []
				startUserSelectAssigneesFormRules.value[userTask.id] = [
					{
						required: true,
						message: '请选择审批人',
						validator: (value: any) => {
							if (value && Array.isArray(value) && value.length > 0) {
								return Promise.resolve();
							} else {
								return Promise.reject('审批人不能为空');
							}
						},
						trigger: ['change']

					}
				]
			}
		}
	} catch (error) {
		toast.error('获取流程定义失败，请重试')
	}
}
//表单项字段配置
const formFields = ref<any[]>([
	{
		type: 'select', prop: 'type', label: '类型', placeholder: '请选择类型',
		options: getIntDictOptions(DICT_TYPE.OA_OUT_TYPE),
		valueKey: 'value',
		labelKey: 'label',
		clearable: true,
		filterable: true,
		showConfirm: false,
		multiple: false,
		onChange: handleTypeChange
	},
	{
		type: 'input',
		prop: 'title',
		label: '标题',
		placeholder: '请输入标题',
		clearable: true,
	},
	{
		type: 'input',
		prop: 'mainRecipient',
		label: '主送',
		placeholder: '请输入主送',
		clearable: true,
	},
	{
		type: 'input',
		prop: 'ccSend',
		label: '抄送',
		placeholder: '请输入抄送',
		clearable: true,
	},
	// {
	// 	type: 'input',
	// 	prop: 'documentNumber',
	// 	label: '发文字号',
	// 	placeholder: '请输入发文字号',
	// 	// inputType: 'number',
	// 	clearable: true,
	// },
	// {
	// 	type: 'input',
	// 	prop: 'proofreader',
	// 	label: '校对人',
	// 	placeholder: '请输入校对人',
	// 	clearable: true,
	// },
	{
		type: 'input',
		prop: 'totalPrinted',
		label: '印份数',
		placeholder: '请输入印份数',
		inputType: 'number',
		clearable: true,
	},
	{
		type: 'upload', prop: 'mainContent', label: '正文', placeholder: '请输入正文',
		action: globalConfig.uploadUrl,
		limit: 1,
		accept: 'all',
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'mainTextUrl',    // 接口返回ID -> formData.serverIds
			fileName: 'mainTextName'     // 文件名 -> formData.fileName
		}
	},
	{
		type: 'upload', prop: 'attachment', label: '附件', placeholder: '请输入附件',
		action: globalConfig.uploadUrl,
		limit: 0,
		isMultipleArray: true,
		accept: 'all',
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'eids',    // 接口返回ID -> formData.serverIds
			fileName: 'ename'     // 文件名 -> formData.fileName
		}
	},

])

const formRules = reactive({
	type: [{ required: true, message: '请选择类型', trigger: 'change' }],
	title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
	mainRecipient: [{ required: true, message: '主送不能为空', trigger: 'blur' }],
	ccReport: [{ required: true, message: '抄报不能为空', trigger: 'blur' }],
	// subjectKeywords: [{ required: true, message: '主题词不能为空', trigger: 'blur' }],
	// documentNumber: [{ required: true, message: '文号不能为空', trigger: 'blur' },],
	// proofreader: [{ required: true, message: '校对人不能为空', trigger: 'blur' },
	// { max: 4, message: '校对人不能超过4个字符', trigger: 'blur' }
	// ],
	totalPrinted: [{ required: true, message: '印发份数不能为空', trigger: 'blur' }],
})

onLoad(async (options) => {
	console.log('字典数据', getIntDictOptions(DICT_TYPE.OA_OUT_TYPE));

	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey.value
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
	const userProfile: any = await getUserProfile()

	formData.value.draftingAuthor = userProfile.nickname
	formData.value.draftingDepartment = userProfile.dept.name
})

/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await postManagementApi.getOutGoing(Number(detailId.value))
		formData.value = data
		// 附件字段回显
		formData.value.eids = parseArrayField(data.eids);
		formData.value.ename = parseArrayField(data.ename);
		fileLists.value.attachment = buildFileList(formData.value.eids, formData.value.ename) as any;
		fileLists.value.mainContent = buildFileList(formData.value.mainTextUrl, formData.value.mainTextName) as any;


	} catch (error) {
		console.log('加载数据失败')
	}
}
/** 提交表单 */
const submitForm = async (payload: any) => {
	console.log('payload', payload);

	try {
		if (payload.type === 'create') {
			console.log('payload.data', payload.data);
			// 调用创建 API
			await postManagementApi.createOutGoing(payload.data)
			toast.success('新增成功');
		} else {
			console.log('payload.data', payload.data);
			// 调用更新 API
			await postManagementApi.updateOutGoing(payload.data)
			toast.success('编辑成功');
		}

		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/outgoingDocument/index' });

	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}
/** 取消表单 */
const cancelForm = async () => {
	if (!message || !toast) {
		console.error('message 或 toast 未初始化，可能未在组件上下文中调用')
		return
	}
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/outgoingDocument/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>